package connect

import (
	"sync"
)

var (
	userGroupMutex sync.RWMutex
)

// 用户组列表（链表结构存储）
type UserGroup struct {
	users *UserNode
}

func NewUserGroup() *UserGroup {
	return &UserGroup{}
}

type UserNode struct {
	User *User
	Next *UserNode
}

func NewUserNode(user *User) *UserNode {
	return &UserNode{
		User: user,
	}
}

func (group *UserGroup) Add(user *User) {
	userGroupMutex.Lock()
	defer userGroupMutex.Unlock()

	userNode := NewUserNode(user)

	if group.users == nil {
		group.users = userNode
		return
	}

	userNode.Next = group.users
	group.users = userNode
}

func (group *UserGroup) Del(userId string) bool {
	userGroupMutex.Lock()
	defer userGroupMutex.Unlock()

	var parent *UserNode
	current := group.users
	for current != nil {
		if current.User.UserId != userId {
			parent = current
			current = current.Next
			continue
		}

		if parent == nil {
			group.users = group.users.Next
			return true
		}

		parent.Next = current.Next
		return true
	}

	return false
}

func (group *UserGroup) Has(userId string) bool {
	userGroupMutex.RLock()
	defer userGroupMutex.RUnlock()

	current := group.users
	for current != nil {
		if current.User.UserId == userId {
			return true
		}
		current = current.Next
	}

	return false
}

func (group *UserGroup) Get(userId string) *User {
	userGroupMutex.RLock()
	defer userGroupMutex.RUnlock()

	current := group.users
	for current != nil {
		if current.User.UserId == userId {
			return current.User
		}
		current = current.Next
	}

	return nil
}

func (group *UserGroup) Len() int {
	userGroupMutex.RLock()
	defer userGroupMutex.RUnlock()

	count := 0

	current := group.users
	for current != nil {
		count++
		current = current.Next
	}

	return count
}

func (group *UserGroup) ForEach(handler func(user *User)) {
	userGroupMutex.RLock()
	defer userGroupMutex.RUnlock()

	current := group.users
	for current != nil {
		handler(current.User)
		current = current.Next
	}
}
